<template>
	<div class="sys-region-container">
		<el-row :gutter="8" style="width: 100%; flex: 1">
			<el-col :span="3" :xs="24">
				<RegionTree ref="regionTreeRef" @node-click="nodeClick" />
			</el-col>

			<el-col :span="21" :xs="24" style="display: flex; flex-direction: column">
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.queryParams" ref="queryForm" :inline="true">
						<el-form-item label="项目">
							<el-input v-model="state.queryParams.roadname" placeholder="项目" clearable />
						</el-form-item>
						<el-form-item label="项目编号">
							<el-input v-model="state.queryParams.roadNo" placeholder="项目编号" clearable />
						</el-form-item>
						<el-form-item>
							<el-button-group>
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'sysRegion:page'"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
							</el-button-group>
						</el-form-item>

					</el-form>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table :data="state.regionData" style="width: 100%" v-loading="state.loading" row-key="id" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border>

						<el-table-column prop="name" width="140"  label="路网类型" align="center" show-overflow-tooltip />
						<el-table-column prop="roadname"  width="140" label="路网全称" align="center" show-overflow-tooltip />
						<el-table-column prop="roadNo"  width="140" label="编号" align="center" show-overflow-tooltip />
						<el-table-column prop="remark"  width="140" label="决策状态" header-align="center" show-overflow-tooltip />
						<el-table-column label="道路数据预览"  fixed="right"  align="center" show-overflow-tooltip>
							<template #default="scope">
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openfiles(scope.row,1)" v-auth="'sysRegion:update'"> 平整度 </el-button>
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openfiles(scope.row,2)" v-auth="'sysRegion:update'"> 车辙 </el-button>
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openfiles(scope.row,3)" v-auth="'sysRegion:update'"> 路面破损 </el-button>
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openfiles(scope.row,4)" v-auth="'sysRegion:update'"> 技术状况评定 </el-button>
							</template>
						</el-table-column>
						<el-table-column label="基础数据"  fixed="right"  align="center" show-overflow-tooltip>
							<template #default="scope">
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openEditRegionjc(scope.row)" v-auth="'sysRegion:update'"> 预览 </el-button>
							</template>
						</el-table-column>
						<el-table-column label="操作"  fixed="right"  align="center" show-overflow-tooltip>
							<template #default="scope">
								<el-button icon="ele-Edit" size="small" text type="primary"  @click="openEditRegionjc(scope.row)" v-auth="'sysRegion:update'"> 发起决策 </el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						v-model:currentPage="state.tableParams.page"
						v-model:page-size="state.tableParams.pageSize"
						:total="state.tableParams.total"
						:page-sizes="[10, 20, 50, 100]"
						small
						background
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
					/>
				</el-card>
			</el-col>
		</el-row>
		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="5" :file-list="state.fileList" action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<EditRegion ref="editRegionRef" :title="state.editRegionTitle" @handleQuery="handleQuery"  :regionData="state.regionData"
		/>
		<el-drawer :title="state.fileName" v-model="state.dialogDocxVisible" size="50%" destroy-on-close>
			<vue-office-docx :src="state.docxUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
		</el-drawer>
		<el-drawer :title="state.fileName" v-model="state.dialogXlsxVisible" size="50%" destroy-on-close>
			<vue-office-excel :src="state.excelUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
			/></el-drawer>
		<el-drawer :title="state.fileName" v-model="state.dialogPdfVisible" size="50%" destroy-on-close>
			<vue-office-pdf :src="state.pdfUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
			/></el-drawer>
		<el-image-viewer v-if="state.showViewer" :url-list="state.previewList" @close="state.showViewer = false"></el-image-viewer>

	</div>
</template>

<script lang="ts" setup name="sysRegion">
import { onMounted, reactive, ref } from 'vue';
import {ElMessageBox, ElMessage, ElNotification, UploadInstance} from 'element-plus';
import RegionTree from '/@/views/system/region/component/regionTree.vue';
import EditRegion from '/@/views/main/decisionfa/component/editRegion.vue';
import {SysFileApi} from '/@/api-services/api';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import { getAPI } from '/@/utils/axios-utils';
import { SysRegionApi } from '/@/api-services/api';
import {SysFile, SysRegion} from '/@/api-services/models';
import { uploadFilesPoject,getjcinfodown,getjcinfo} from "/@/api/region/region";
import MapDragRoute from "/@/views/map/MapDragRoute.vue";






const uploadRef = ref<UploadInstance>();
const editRegionRef = ref<InstanceType<typeof EditRegion>>();
const regionTreeRef = ref<InstanceType<typeof RegionTree>>();
const state = reactive({
	loading: false,
	key:0,
	Pid : undefined,
	fileData: [] as Array<SysFile>,
	fileList: [] as any,
	fileName: '',
	regionData: [] as Array<SysRegion>, // 列表数据
	queryParams: {
		id: -1,
		pid: undefined,
		roadname: undefined,
		roadNo: undefined,
		year:"2023",
	},
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0 as any,
	},
	editRegionTitle: '',
	diaglogEditFile: false,
	dialogDocxVisible: false,
	dialogXlsxVisible: false,
	dialogPdfVisible: false,
	showViewer: false,
	docxUrl: '',
	excelUrl: '',
	pdfUrl: '',
	previewList: [] as string[],
});

onMounted(() => {
	handleQuery();
});


// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	state.fileList = fileList;
	console.log('实例',state)
};

// 取消
const cancel = () => {
	state.fileList = [];
	state.isShowDialog = false;
};
// 打开上传页面
const openUploadDialog = (row: any,key:any) => {
	state.fileList = [];
	state.Pid=row.id;
	state.key=key;
	state.dialogUploadVisible = true;
};

// 上传
const uploadFile = async () => {
	const params = new FormData();

	if (state.fileList.length >=1){
		for (let i = 0; i < state.fileList.length; i++) {
			state.fileList[i].pid = state.Pid;
			params.append('files', state.fileList[i].raw);
		}
		params.append('pid',state.Pid);
		params.append('key',state.key);
		await uploadFilesPoject(params);
	}
	handleQuery();
	state.key=0;
	state.Pid=0;
	state.dialogUploadVisible = false;
};

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	var res = await getAPI(SysRegionApi).apiSysRegionPagePost(params);
	state.regionData = (res.data.result?.items ?? []).filter((item: SysRegion) => item.level === 4);
	state.tableParams.total = res.data.result?.total;
	state.loading = false;
};

// 打开文件预览页面
const openFilePreviewDialog = async (row: any) => {
		console.log('传入参数',row)
	if (row.suffix == '.pdf') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.pdfUrl = getFileUrl(row);
		state.dialogPdfVisible = true;
	} else if (row.suffix == '.docx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.docxUrl = getFileUrl(row);
		state.dialogDocxVisible = true;
	} else if (row.suffix == '.xlsx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.excelUrl = getFileUrl(row);
		state.dialogXlsxVisible = true;
	} else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex((e) => e == row.suffix) > -1) {
		state.previewList = [getFileUrl(row)];
		state.showViewer = true;
	} else {
		ElMessage.error('此文件格式不支持预览');
	}
};

const openfiles =async (row: any,index:any)=>{

	const files=row.files;
	// 迭代 files 集合
	for (const file of files) {
		if (index === 1 && file.fileName.includes('平整度')) {
			openFilePreviewDialog(file);
		}
		if (index === 2 && file.fileName.includes('车辙')) {
			openFilePreviewDialog(file);
		}
		if (index === 3 && file.fileName.includes('路面破损')) {
			openFilePreviewDialog(file);
		}
		if (index === 4 && file.fileName.includes('技术状况评定')) {
			openFilePreviewDialog(file);
		}
	}

}

// 获取文件地址
const getFileUrl = (row: SysFile): string => {
	if (row.bucketName == 'Local') {
		return `/${row.filePath}/${row.id}${row.suffix}`;
	} else {
		return row.url!;
	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.id = -1;
	state.queryParams.pid = undefined;
	state.queryParams.name = undefined;
	state.queryParams.code = undefined;
	handleQuery();
};

// 打开新增页面
const openAddRegion = () => {
	state.editRegionTitle = '添加项目';
	editRegionRef.value?.openDialog({ orderNo: 100 });
};

const openEditRegionjc = (row: any) => {
	state.editRegionTitle = '编辑行政区域';
	console.log("看年度",state.queryParams.year )
	editRegionRef.value?.openDialog(row);
};



// 删除
const delRegion = (row: any) => {
	ElMessageBox.confirm(`确定删除行政区域：【${row.name}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysRegionApi).apiSysRegionDeletePost({ id: row.id });
			handleQuery();
			// 编辑删除后更新机构数据
			regionTreeRef.value?.initTreeData();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 树组件点击
const nodeClick = async (node: any) => {
	state.queryParams.pid = node.id;
	state.queryParams.year = node.syear;
	console.log("看年度111",node.syear )

	state.queryParams.name = undefined;
	state.queryParams.code = undefined;

	handleQuery();
};



// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
